from data_access.database import Session
from sqlalchemy.exc import SQLAlchemyError

from data_access.models.models import Service


class ServiceDAO:
    def __init__(self):
        self.session = Session()

    def add_service(self, center_dispatch_code, dispatch_code, service_level, service_id, service_name, service_host, service_port, service_type, service_url, comment=None):
        new_service = Service(
            center_dispatch_code=center_dispatch_code,
            dispatch_code=dispatch_code,
            service_level=service_level,
            service_id=service_id,
            service_name=service_name,
            service_host=service_host,
            service_port=service_port,
            service_type=service_type,
            service_url=service_url,
            comment=comment
        )
        try:
            self.session.add(new_service)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def get_service_by_service_id(self, dispatch_code, service_id):
        try:
            return self.session.query(Service).filter(Service.dispatch_code == dispatch_code, Service.service_id == service_id).first()
        except SQLAlchemyError as e:
            return None
        finally:
            self.session.close()

    def update_service(self, service_id, **kwargs):
        try:
            self.session.query(Service).filter(Service.service_id == service_id).update(kwargs)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def delete_service(self, service_id):
        try:
            self.session.query(Service).filter(Service.service_id == service_id).delete()
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()
